package com.multiplesource.config;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import com.alibaba.druid.util.StringUtils;

/**
 * 通过springboot启动添加自定义bean的处理
 * 
 * @author zhuzhoutong
 *
 */
public class MultiInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>{

	@Override
	public void initialize(ConfigurableApplicationContext applicationContext) {
		Environment ev = applicationContext.getEnvironment();
		MultiDataSourceProperties pp = new MultiDataSourceProperties();
		initProperties(pp,ev);
		applicationContext.addBeanFactoryPostProcessor(new MultiDataSourceProcessor(pp));		
	}
	
	/**
	 * 加载环境属性变量
	 * @param prop
	 * @param env
	 */
	private void initProperties(MultiDataSourceProperties prop,Environment env){
		String datasourcenames = env.getProperty(MultiDataSourceProperties.PREFIX+".name");
		if(StringUtils.isEmpty(datasourcenames)) {
			return ;
		}
		String[] sourcenames = datasourcenames.split(",");
		prop.setNames(sourcenames);
		Map<String,SingleDataSourceProperties> sps = new HashMap<String,SingleDataSourceProperties>();
		prop.setProperties(sps);
		Field[] fields = SingleDataSourceProperties.class.getDeclaredFields();
		for(int i=0;i<sourcenames.length;i++) {
			SingleDataSourceProperties sp = new SingleDataSourceProperties();
			sps.put(sourcenames[i], sp);
			StringBuffer realnamebuf = new StringBuffer(MultiDataSourceProperties.PREFIX);
			realnamebuf.append(".");
			realnamebuf.append(sourcenames[i]);
			realnamebuf.append(".");
			for(int k=0;k<fields.length;k++) {
				Field field = fields[k];
				String fieldname = field.getName();
				String realname = realnamebuf.toString()+fieldname;
				if(env.containsProperty(realname)) {
					try {
						String firstLetter = fieldname.substring(0,1).toUpperCase();
						String methodname_set = "set"+ firstLetter + fieldname.substring(1);
						Method setMethod = SingleDataSourceProperties.class.getMethod(methodname_set, new Class[]{field.getType()});
						setMethod.invoke(sp, new Object[]{env.getProperty(realname)});
					}catch (Exception e) {
					}
				}
			}
		}
	}

}
